from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json


@csrf_exempt
@require_http_methods(["POST"])
def user_login(request):
    """用户登录"""
    try:
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return JsonResponse({
                'code': 400,
                'message': '用户名和密码不能为空'
            }, status=400)
        
        # 认证用户
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            if user.is_active:
                # 登录成功
                login(request, user)
                
                # 获取用户扩展信息
                user_data = {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'first_name': user.first_name,
                    'last_name': user.last_name,
                }
                
                # 如果有用户扩展信息，添加到响应中
                if hasattr(user, 'profile'):
                    profile = user.profile
                    user_data.update({
                        'nickname': profile.nickname,
                        'avatar': profile.avatar.url if profile.avatar else None,
                        'phone': profile.phone,
                        'school': profile.school,
                        'major': profile.major,
                        'grade': profile.grade,
                        'student_id': profile.student_id,
                        'is_verified': profile.is_verified,
                        'credit_score': str(profile.credit_score),
                        'volunteer_hours': str(profile.volunteer_hours),
                    })
                
                return JsonResponse({
                    'code': 200,
                    'message': '登录成功',
                    'data': user_data
                })
            else:
                return JsonResponse({
                    'code': 403,
                    'message': '账号已被禁用'
                }, status=403)
        else:
            return JsonResponse({
                'code': 401,
                'message': '用户名或密码错误'
            }, status=401)
            
    except json.JSONDecodeError:
        return JsonResponse({
            'code': 400,
            'message': '无效的JSON数据'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["POST"])
def user_logout(request):
    """用户登出"""
    try:
        if request.user.is_authenticated:
            logout(request)
            return JsonResponse({
                'code': 200,
                'message': '登出成功'
            })
        else:
            return JsonResponse({
                'code': 400,
                'message': '用户未登录'
            }, status=400)
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["POST"])
def user_register(request):
    """用户注册"""
    try:
        data = json.loads(request.body)
        username = data.get('username')
        email = data.get('email')
        password = data.get('password')
        school = data.get('school')
        
        # 验证必填字段
        if not all([username, email, password, school]):
            return JsonResponse({
                'code': 400,
                'message': '用户名、邮箱、密码和学校为必填项'
            }, status=400)
        
        # 检查用户名是否已存在
        if User.objects.filter(username=username).exists():
            return JsonResponse({
                'code': 400,
                'message': '用户名已存在'
            }, status=400)
        
        # 检查邮箱是否已存在
        if User.objects.filter(email=email).exists():
            return JsonResponse({
                'code': 400,
                'message': '邮箱已被注册'
            }, status=400)
        
        # 创建用户
        user = User.objects.create_user(
            username=username,
            email=email,
            password=password
        )
        
        # 创建用户扩展信息
        from users_extend.models import UserProfile
        UserProfile.objects.create(
            user=user,
            school=school,
            nickname=data.get('nickname', username),
            phone=data.get('phone'),
            major=data.get('major'),
            grade=data.get('grade'),
            student_id=data.get('student_id'),
        )
        
        # 自动登录
        login(request, user)
        
        return JsonResponse({
            'code': 200,
            'message': '注册成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
            }
        })
        
    except json.JSONDecodeError:
        return JsonResponse({
            'code': 400,
            'message': '无效的JSON数据'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }, status=500)


@require_http_methods(["GET"])
def user_info(request):
    """获取当前用户信息"""
    try:
        if not request.user.is_authenticated:
            return JsonResponse({
                'code': 401,
                'message': '用户未登录'
            }, status=401)
        
        user = request.user
        user_data = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name,
            'is_staff': user.is_staff,
            'is_active': user.is_active,
            'date_joined': user.date_joined.strftime('%Y-%m-%d %H:%M:%S'),
        }
        
        # 添加用户扩展信息
        if hasattr(user, 'profile'):
            profile = user.profile
            user_data.update({
                'nickname': profile.nickname,
                'avatar': profile.avatar.url if profile.avatar else None,
                'phone': profile.phone,
                'school': profile.school,
                'major': profile.major,
                'grade': profile.grade,
                'student_id': profile.student_id,
                'is_verified': profile.is_verified,
                'credit_score': str(profile.credit_score),
                'volunteer_hours': str(profile.volunteer_hours),
                'bio': profile.bio,
                'preferences': profile.preferences,
                'favorite_categories': profile.favorite_categories,
                'reading_interests': profile.reading_interests,
            })
        
        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': user_data
        })
        
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["PUT", "PATCH"])
def update_user_info(request):
    """更新用户信息"""
    try:
        if not request.user.is_authenticated:
            return JsonResponse({
                'code': 401,
                'message': '用户未登录'
            }, status=401)
        
        data = json.loads(request.body)
        user = request.user
        
        # 更新用户基本信息
        if 'first_name' in data:
            user.first_name = data['first_name']
        if 'last_name' in data:
            user.last_name = data['last_name']
        if 'email' in data:
            # 检查邮箱是否已被其他用户使用
            if User.objects.filter(email=data['email']).exclude(id=user.id).exists():
                return JsonResponse({
                    'code': 400,
                    'message': '邮箱已被使用'
                }, status=400)
            user.email = data['email']
        
        user.save()
        
        # 更新用户扩展信息
        if hasattr(user, 'profile'):
            profile = user.profile
            
            if 'nickname' in data:
                profile.nickname = data['nickname']
            if 'phone' in data:
                profile.phone = data['phone']
            if 'school' in data:
                profile.school = data['school']
            if 'major' in data:
                profile.major = data['major']
            if 'grade' in data:
                profile.grade = data['grade']
            if 'student_id' in data:
                profile.student_id = data['student_id']
            if 'bio' in data:
                profile.bio = data['bio']
            if 'preferences' in data:
                profile.preferences = data['preferences']
            if 'favorite_categories' in data:
                profile.favorite_categories = data['favorite_categories']
            if 'reading_interests' in data:
                profile.reading_interests = data['reading_interests']
            
            profile.save()
        
        return JsonResponse({
            'code': 200,
            'message': '更新成功'
        })
        
    except json.JSONDecodeError:
        return JsonResponse({
            'code': 400,
            'message': '无效的JSON数据'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }, status=500)


@csrf_exempt
@require_http_methods(["POST"])
def change_password(request):
    """修改密码"""
    try:
        if not request.user.is_authenticated:
            return JsonResponse({
                'code': 401,
                'message': '用户未登录'
            }, status=401)
        
        data = json.loads(request.body)
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        
        if not old_password or not new_password:
            return JsonResponse({
                'code': 400,
                'message': '旧密码和新密码不能为空'
            }, status=400)
        
        user = request.user
        
        # 验证旧密码
        if not user.check_password(old_password):
            return JsonResponse({
                'code': 400,
                'message': '旧密码错误'
            }, status=400)
        
        # 设置新密码
        user.set_password(new_password)
        user.save()
        
        # 重新登录
        login(request, user)
        
        return JsonResponse({
            'code': 200,
            'message': '密码修改成功'
        })
        
    except json.JSONDecodeError:
        return JsonResponse({
            'code': 400,
            'message': '无效的JSON数据'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }, status=500)